package com.joe.blockview.listener;

import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import com.joe.blockview.model.Connection;
import com.joe.blockview.ui.BlockView;
import com.joe.blockview.utils.ScreenUtils;
import com.joe.blockview.ui.WorkSpace;

public class OnDragTouchListener implements View.OnTouchListener {
    private int mScreenWidth, mScreenHeight;//父控件宽高
    private float mOriginalX, mOriginalY;//手指按下时的初始位置
    private int originalLeft, originalTop;
    private float mDistanceX, mDistanceY;//记录手指与view的左上角的距离
    private int left, top, right, bottom;
    private OnDraggableClickListener mListener;
    private long startTime;
    private long endTime;
//    private boolean hasAutoPullToBorder;//标记是否开启自动拉到边缘功能

    public OnDragTouchListener() {
    }

//    public OnDragTouchListener(boolean isAutoPullToBorder) {
//        hasAutoPullToBorder = isAutoPullToBorder;
//    }

    @Override
    public boolean onTouch(final View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startTime = System.currentTimeMillis();
                ViewGroup mViewGroup = (ViewGroup) v.getParent();
                mScreenWidth = mViewGroup.getMeasuredWidth();
                mScreenHeight = mViewGroup.getMeasuredHeight();
                originalLeft = v.getLeft();
                originalTop = v.getTop();
                mOriginalX = event.getRawX();
                mOriginalY = event.getRawY();
                mDistanceX = event.getRawX() - v.getLeft();
                mDistanceY = event.getRawY() - v.getTop();
                break;
            case MotionEvent.ACTION_MOVE:
                left = (int) (event.getRawX() - mDistanceX);
                top = (int) (event.getRawY() - mDistanceY);
                WorkSpace wk = (WorkSpace) v.getParent();
                right = left + v.getWidth();
                bottom = top + v.getHeight();
                if (left < 0 + wk.getScrollX()) {
                    left = 0 + wk.getScrollX();
                    right = left + v.getWidth();
                }
                if (top < 0 + wk.getScrollY()) {
                    top = 0 + wk.getScrollY();
                    bottom = top + v.getHeight();
                }
                if (right > mScreenWidth + wk.getScrollX()) {
                    right = mScreenWidth + wk.getScrollX();
                    left = right - v.getWidth();
                }
                if (bottom > mScreenHeight + wk.getScrollY()) {
                    bottom = mScreenHeight + wk.getScrollY();
                    top = bottom - v.getHeight();
                }

                v.layout(left, top, right, bottom);
                BlockView bv = (BlockView) v;
                if (bv.getConnection().getType() == 2) {
                    Connection inp = bv.getConnection().getInputConnection();
                    if (inp != null) {
                        BlockView blockViewp = inp.getTagBlockView();
                        int ls = (int) inp.getWorkspacePoint().x + left - originalLeft;
                        int ts = (int) inp.getWorkspacePoint().y + top - originalTop;
                        int rs = ls + bv.getWidth();
                        int bs = ts + bv.getHeight();
                        blockViewp.layout(ls, ts, rs, bs);
                    }
                }

                if (Math.abs(event.getRawX() - mOriginalX) >
                        ScreenUtils.getPxFromDp(v.getResources(), 5) ||
                        Math.abs(event.getRawY() - mOriginalY) >
                                ScreenUtils.getPxFromDp(v.getResources(), 5)) {
                    if (mListener != null) {
                        mListener.onMove(v, left, top);
                    }
                }
                //获取blockview之后的所有关联，同步移动
                BlockView tag = (BlockView) v;
                int i = 0;
                while (tag != null && i < 100) {
                    i++;
                    Connection tagConnection = tag.getConnection().getTagConnection();
                    //-----------------------------
                    //添加内部链移动
                    dragNextLine(tag);
                    //------------------------
                    if (tagConnection != null) {
                        tag = tagConnection.getTagBlockView();
                        int l = (int) tagConnection.getWorkspacePoint().x + left - originalLeft;
                        int t = (int) tagConnection.getWorkspacePoint().y + top - originalTop;
                        int r = l + tag.getWidth();
                        int b = t + tag.getHeight();
                        tag.layout(l, t, r, b);
                        if (tag.getConnection().getType() == 2) {
                            Connection inp = tag.getConnection().getInputConnection();
                            if (inp != null) {
                                BlockView blockViewp = inp.getTagBlockView();
                                int ls = (int) inp.getWorkspacePoint().x + left - originalLeft;
                                int ts = (int) inp.getWorkspacePoint().y + top - originalTop;
                                int rs = ls + tag.getWidth();
                                int bs = ts + tag.getHeight();
                                blockViewp.layout(ls, ts, rs, bs);
                            }
                        }
                    } else {
                        tag = null;
                    }
                }

                break;
            case MotionEvent.ACTION_UP:
                endTime = System.currentTimeMillis();
                //如果移动距离过小，按下，抬起时间过短，则判定为点击
                if ((endTime - startTime) < 0.1 * 1000L && Math.abs(event.getRawX() - mOriginalX) <
                        ScreenUtils.getPxFromDp(v.getResources(), 5) &&
                        Math.abs(event.getRawY() - mOriginalY) <
                                ScreenUtils.getPxFromDp(v.getResources(), 5)) {
                    if (mListener != null) {
                        mListener.onClick(v);
                    }
                } else {
                    if (mListener != null) {
                        mListener.onDragged(v, left, top);
                    }
                }
                //消除警告
                v.performClick();
                break;
        }
        return true;
    }

    /**
     * 内部链接跟随拖动
     *
     * @param tag
     */
    public void dragNextLine(BlockView tag) {
        if (tag.getConnection().getType() == 2 || tag.getConnection().getType() == 3) {
            if (tag.getConnection().getType() == 2) {
                Connection inp = tag.getConnection().getInputConnection();
                if (inp != null) {
                    BlockView blockViewp = inp.getTagBlockView();
                    int ls = (int) inp.getWorkspacePoint().x + left - originalLeft;
                    int ts = (int) inp.getWorkspacePoint().y + top - originalTop;
                    int rs = ls + tag.getWidth();
                    int bs = ts + tag.getHeight();
                    blockViewp.layout(ls, ts, rs, bs);
                }
            }
            //判断是否有内部链
            Connection nextConnect = tag.getConnection().getNextConnection();
            if (nextConnect != null) {
                BlockView next = nextConnect.getTagBlockView();
                int j = 0;
                while (next != null && j < 30) {
                    j++;
                    //内部嵌套内部循环调用
                    dragNextLine(next);

                    int l = (int) next.getConnection().getWorkspacePoint().x + left - originalLeft;
                    int t = (int) next.getConnection().getWorkspacePoint().y + top - originalTop;
                    int r = l + next.getWidth();
                    int b = t + next.getHeight();
                    next.layout(l, t, r, b);
                    nextConnect = nextConnect.getTagConnection();
                    if (nextConnect != null) {
                        next = nextConnect.getTagBlockView();
                    } else {
                        next = null;
                    }
                }
            }
        }
    }

    public OnDraggableClickListener getOnDraggableClickListener() {
        return mListener;
    }

    public void setOnDraggableClickListener(OnDraggableClickListener listener) {
        mListener = listener;
    }

//    public boolean isHasAutoPullToBorder() {
//        return hasAutoPullToBorder;
//    }
//
//    public void setHasAutoPullToBorder(boolean hasAutoPullToBorder) {
//        this.hasAutoPullToBorder = hasAutoPullToBorder;
//    }

    /**
     * 开启自动拖拽
     *
     * @param v  拉动控件
     * @param lp 控件布局参数
     */
    private void startAutoPull(final View v, final ViewGroup.LayoutParams lp) {
//        if (!hasAutoPullToBorder) {
//            v.layout(left, top, right, bottom);
//            lp.setMargins(left, top, 0, 0);
//            v.setLayoutParams(lp);
//            if (mListener != null) {
//                mListener.onDragged(v, left, top);
//            }
//            return;
//        }
//        //当用户拖拽完后，让控件根据远近距离回到最近的边缘
//        float end = 0;
//        if ((left + v.getWidth() / 2) >= mScreenWidth / 2) {
//            end = mScreenWidth - v.getWidth();
//        }
//        ValueAnimator animator = ValueAnimator.ofFloat(left, end);
//        animator.setInterpolator(new DecelerateInterpolator());
//        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//            @Override
//            public void onAnimationUpdate(ValueAnimator animation) {
//                int leftMargin = (int) ((float) animation.getAnimatedValue());
//                v.layout(leftMargin, top, right, bottom);
//                lp.setMargins(leftMargin, top, 0, 0);
//                v.setLayoutParams(lp);
//            }
//        });
//        final float finalEnd = end;
//        animator.addListener(new AnimatorListenerAdapter() {
//            @Override
//            public void onAnimationEnd(Animator animation) {
//                super.onAnimationEnd(animation);
//                if (mListener != null) {
//                    mListener.onDragged(v, (int) finalEnd, top);
//                }
//            }
//        });
//        animator.setDuration(400);
//        animator.start();
    }

    /**
     * 控件拖拽监听器
     */
    public interface OnDraggableClickListener {

        /**
         * 当控件在移动过程中
         *
         * @param v
         * @param left
         * @param top
         */
        void onMove(View v, int left, int top);

        /**
         * 当控件拖拽完后回调
         *
         * @param v    拖拽控件
         * @param left 控件左边距
         * @param top  控件右边距
         */
        void onDragged(View v, int left, int top);

        /**
         * 当可拖拽控件被点击时回调
         *
         * @param v 拖拽控件
         */
        void onClick(View v);
    }
}
